package org.mybatis.generator.config.xml;

import java.util.Enumeration;
import java.util.Properties;

import org.mybatis.generator.config.PropertyHolder;
import org.mybatis.generator.config.TypedPropertyHolder;

public abstract class GeneratorUtils {

	/**
	 * 创建 TypedPropertyHolder
	 */
	public static <T extends TypedPropertyHolder> T newInstance(Class<T> holderClass, String configurationType,
			Properties attributes) {
		T holder = newInstance(holderClass, attributes);
		holder.setConfigurationType(configurationType);
		return holder;
	}

	/**
	 * 创建 PropertyHolder
	 */
	public static <T extends PropertyHolder> T newInstance(Class<T> holderClass, Properties attributes) {
		T holder = newInstance(holderClass);
		addAllProperty(holder, attributes);
		return holder;
	}

	// 添加属性
	public static void addAllProperty(PropertyHolder holder, Properties attributes) {
		if (attributes == null) return;
		Enumeration<?> propertyNames = attributes.propertyNames();
		while (propertyNames.hasMoreElements()) {
			String name = (String) propertyNames.nextElement();
			holder.addProperty(name, attributes.getProperty(name));
		}
	}

	public static String parsePropertyTokens(String string, Properties properties) {
		if (properties == null || properties.size() <= 0) return string;
		final String OPEN = "${";
		final String CLOSE = "}";

		String newString = string;
		if (newString != null) {
			int start = newString.indexOf(OPEN);
			int end = newString.indexOf(CLOSE);

			while (start > -1 && end > start) {
				String prepend = newString.substring(0, start);
				String append = newString.substring(end + CLOSE.length());
				String propName = newString.substring(start + OPEN.length(), end);
				String propValue = properties.getProperty(propName);
				if (propValue != null) {
					newString = prepend + propValue + append;
				}

				start = newString.indexOf(OPEN, end);
				end = newString.indexOf(CLOSE, end);
			}
		}

		return newString;
	}

	private static <T> T newInstance(Class<T> clazz) {
		try {
			return clazz.newInstance();
		} catch (Exception e) {
			throw new RuntimeException("class[" + clazz.getName() + "] 没有默认构造函数.", e);
		}
	}

}
